package com.tledu.web04.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

import static com.tledu.web04.constants.CommonConstants.VIEW_PREFIX;

@WebServlet("/cookie")
public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 向客户端传递cookie
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        Cookie cookie = new Cookie("token", "这是我们访问系统的凭证");
        cookie.setMaxAge(2 * 60 * 60);
        cookie.setPath("/");
//        cookie.setDomain();
        // 只用于http传输，客户端不可被修改
        cookie.setHttpOnly(true);
        resp.addCookie(cookie);


        // 设施session，往session域里放置数据。 cookie是存储在客户端，session是在服务端保存的数据，它们是通过JESSIONID进行关联
        HttpSession session = req.getSession();
        session.setAttribute("name", "张三");

        Cookie cookie1 = new Cookie("JSESSIONID", session.getId());
        cookie1.setMaxAge(60 * 60 * 24);
        cookie1.setHttpOnly(true);
        resp.addCookie(cookie1);
        req.getRequestDispatcher(VIEW_PREFIX + "/cookie.jsp").forward(req, resp);
    }
}
